//
//  WebView.swift
//  MD5
//
//  Created by 郑东喜 on 2016/11/22.
//  Copyright © 2016年 郑东喜. All rights reserved.
//

import UIKit
import WebKit


class WebView: UIViewController,WKUIDelegate,WKScriptMessageHandler {

    
    var webView = WKWebView()
    
    var aaa : String = ""
    
    
//    var webView = WKWebView()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        //wkwebview相关配置
        
        
        //创建并配置WKWebView的相关参数
        //1.WKWebViewConfiguration:是WKWebView初始化时的配置类，里面存放着初始化WK的一系列属性；
        //2.WKUserContentController:为JS提供了一个发送消息的通道并且可以向页面注入JS的类，WKUserContentController对象可以添加多个scriptMessageHandler；
        //3.addScriptMessageHandler:name:有两个参数，第一个参数是userContentController的代理对象，第二个参数是JS里发送postMessage的对象。添加一个脚本消息的处理器,同时需要在JS中添加，window.webkit.messageHandlers.<name>.postMessage(<messageBody>)才能起作用。
        let configuration = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        
        userContentController.add(self as WKScriptMessageHandler, name: "shareWeixinInfo")
        
        //AppModel
        userContentController.add(self as WKScriptMessageHandler, name: "AppModel")
        
        configuration.userContentController = userContentController
        
        let preferences = WKPreferences()
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        configuration.preferences = preferences
        
        webView.uiDelegate = self
        
        webView = WKWebView.init(frame: view.bounds, configuration: configuration)
        
        
        //本地加载
        let htmlPath = Bundle.main.path(forResource: "WKWebViewMessageHandler", ofType: "html")
        
        
        do {
            let fileURL = try NSString.init(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)
            let baseURL = NSURL.fileURL(withPath: htmlPath! as String)
            webView.loadHTMLString(fileURL as String, baseURL: baseURL)
        } catch  {
            
        }
        

        view.addSubview(webView)

        
        //添加监听器
//        webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil)
    }
    
    //移除监听器
//    deinit{
//        webView.removeObserver(self, forKeyPath: "loading")
//    }
    
    
    /**
     *  JS 调用 swift 时 webview 会调用此方法
     *
     *  @param userContentController  webview中配置的userContentController 信息
     *  @param message                JS执行传递的消息
     */

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.body)
        let msg = message.name
        
        if msg == "shareWeixinInfo" {
            print("shareWeixinInfo")

            let asign = "biz_content=%7b%22timeout_express%22%3a%2230m%22%2c%22out_trade_no%22%3a%221201185818872109321%22%2c%22subject%22%3a%22%e4%b8%80%e5%85%83%e8%b4%ad%e8%ae%a2%e5%8d%95%22%2c%22total_amount%22%3a%220.01%22%2c%22body%22%3a%22%e4%b8%80%e5%85%83%e8%b4%ad%e8%ae%a2%e5%8d%95%22%7d&method=alipay.trade.app.pay&version=1.0&app_id=2016030601188528&format=json&timestamp=2016-12-01+18%3a58%3a18&sign_type=RSA&charset=utf-8&notify_url=http%3a%2f%2fyungou.ie1e.com%2fapp%2fpaynotify.aspx&sign=Vv8U5%2b5bb%2bk3YU9LS0UpIvwfK8Qe14sgK0kuG%2f%2bdxLccfaR5jjb58%2fs0pZ5L%2fBn2gPLuUscpk%2b9qN6LEtqqLTihH11RcWj8GU6W%2fu%2fexQqlBHfE3Y8KQWQl8j8QtvAMkHwCj39ogfGyx2Z%2bu0MR0uXqlQZcEfvF%2fsKdYqm2OLr8%3d"

            
            //接收Web支付回调
            PaymenyModel.shared.alipay(orderString: asign, comfun: { (dic) in

                print("\((#file as NSString).lastPathComponent):(\(#line))")
                print(dic)

                self.webView.evaluateJavaScript("callJsAlert('\(dic)')", completionHandler: nil)
            })
            

            NotificationCenter.default.addObserver(self, selector: #selector(WebView.info(notification:)), name: NSNotification.Name(rawValue: "123"), object: nil)
        }
    }

    

}

// MARK:- 接收支付宝app接收结果
extension WebView {
    func info(notification : NSNotification) -> Void {
        print("接收通知")
        let dic = notification.userInfo as! [AnyHashable : NSObject] as NSDictionary
        
        let result = dic["re"] as! String
        print(result)
        
        self.webView.evaluateJavaScript("callJsAlert('\(result)')", completionHandler: nil)

        
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "123"), object: nil)
    }
}

